package com.pj.lib.auraServer.components.lbs;

import java.sql.SQLException;

import java.util.Date;
import java.util.HashMap;

import com.pj.lib.auraServer.app.Server;
import com.pj.lib.auraServer.app.ServerComponent;
import com.pj.lib.auraServer.app.listeners.OnLocationUpdate;
import com.pj.lib.auraServer.components.DB.DB;
import com.pj.lib.auraServer.components.DB.DBComponent;
import com.pj.lib.auraServer.components.DB.tables.UserLocation;
import com.pj.lib.auraServer.exceptions.AuraServerException;

import com.pj.lib.aura.connection.LocationModel;
import com.pj.lib.auraServer.utils.Log;

public class LBSComponent extends ServerComponent{

	private DB mDB;
	
	public LBSComponent(Server server) {
		super(server);
		mDB = ((DBComponent)getServer().getComponent(COMPONENT_DB)).getDB();
		
		addOnUpdateLocation(new OnLocationUpdate() {
			
			@Override
			public void locationReceived(int userId, double[] loc, float precision) {
				onUpdateLocalization(userId, loc, precision );
			}
		});
	}
	

	/**
	 * Function fires on OnUpdateLocation event
	 * @param userID user id in db
	 * @param loc loc[longitude, latitude]  
	 * @param precision precision of locaiton
	 */
	private void onUpdateLocalization(int userID, double[] loc, float precision) {
		HashMap<String, Object> toDB= new HashMap<String, Object>();
		toDB.put(UserLocation.COLUMN_LONGITUDE, loc[0]);
		toDB.put(UserLocation.COLUMN_LATITUDE, loc[1]);
		toDB.put(UserLocation.COLUMN_PRECISION, precision);
		toDB.put(UserLocation.COLUMN_USER_ID, userID);
		toDB.put(UserLocation.COLUMN_TIME, new Date());
		

		
		try {
			((UserLocation)getDB().getInstance(DB.INSTANCE_USER_LOCATION)).add(toDB);
			LocationModel tempLocation = new LocationModel(userID, 
					loc[1], loc[0], 
					(Date) toDB.get(UserLocation.COLUMN_TIME), 
					precision);
			fireLocationUpdatedEvent(tempLocation);
		} catch (AuraServerException e) {
			Log.s(this, Log.getStackTrace(e));
		} catch (SQLException e) {
			Log.s(this, Log.getStackTrace(e));
		}
	}
	
	

}
